package controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import model.Blog;
import model.BlogDao;
import model.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * Description: 这个类用来处理博客列表页的相关方法
 */
@WebServlet("/blogList")
public class BlogListServlet extends HttpServlet {
    private ObjectMapper objectMapper = new ObjectMapper();
    // get方法用来构造博客列表页页面加载的响应
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("application/json; charset=utf8");
        // 根据请求中的cookie获取会话
        HttpSession session = req.getSession(false);
        // 会话中包含了user
        User user = (User) session.getAttribute("user");
        int userId = user.getUserId();

        // 准备工作，之后需要根据不同请求返回不同的博客列表页
        BlogDao blogDao = new BlogDao();
        List<Blog> blogs = null;
        // 判断是获取所有博客还是自己的博客
        String Content = req.getParameter("Content");
        if(Content == null) {
            // 显示所有博客
            blogs = blogDao.selectAll();
        }else {
            // 显示自己的博客
            blogs = blogDao.selectAll(userId);
        }
        // 通过返回的博客顺序表，构造json响应
        String respJson = objectMapper.writeValueAsString(blogs);
        resp.getWriter().write(respJson);
    }
}
